//
//  NSAttributedString+XYAdd.m
//  PeiJue
//
//  Created by lxy on 2017/9/28.
//  Copyright © 2017年 lixiya. All rights reserved.
//

#import "NSAttributedString+XYAdd.h"

@implementation NSAttributedString (XYAdd)
- (CGSize)xy_sizeForFont:(UIFont *)font size:(CGSize)size {
    CGRect rect = [self boundingRectWithSize:size
                                     options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                     context:nil];
    return rect.size;
}



- (CGFloat)xy_widthForFont:(UIFont *)font {
    CGSize size = [self xy_sizeForFont:font size:CGSizeMake(HUGE, HUGE)];
    return size.width;
}


- (CGFloat)xy_heightForFont:(UIFont *)font width:(CGFloat)width {
    CGSize size = [self xy_sizeForFont:font size:CGSizeMake(width, HUGE)];
    return size.height;
}


/** 由多个attributedString拼接成新的attributedString，item意为由text或image生成的单个attributedString */
+ (NSAttributedString *)fixAttributeStrWithItems:(NSArray *)items
{
    NSMutableAttributedString *resultMAttrStr = [[NSMutableAttributedString alloc] init];
    for(int i=0; i<items.count; i++)
    {
        if([items[i] isKindOfClass:[NSAttributedString class]]){
            [resultMAttrStr appendAttributedString:items[i]];
        }
    }
    
    return resultMAttrStr;
}


// 由text生成attributedString
+ (NSAttributedString *)attributedStrWithText:(NSString *)text textColor:(UIColor *)color textFont:(UIFont *)font
{
    NSMutableAttributedString *mAttrStr = [[NSMutableAttributedString alloc] initWithString:text];
    [mAttrStr addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, text.length)];
    [mAttrStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, text.length)];
    
    return mAttrStr;
}

/**文字距离UILabel底部基线的高度，设置文字居中的*/
+ (NSAttributedString *)attributedStrWithText:(NSString *)text textColor:(UIColor *)color textFont:(UIFont *)font baselineOffset:(CGFloat)offSet {
    
    NSMutableAttributedString *mAttrStr = [[NSMutableAttributedString alloc] initWithString:text];
    [mAttrStr addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, text.length)];
    [mAttrStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, text.length)];
    [mAttrStr addAttribute:NSBaselineOffsetAttributeName value:@(offSet) range:NSMakeRange(0, text.length)];
    
    return mAttrStr;
}


// 由image生成attributedString
+ (NSAttributedString *)attributedStrWithImage:(UIImage *)image imageBounds:(CGRect)bounds
{
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    attachment.bounds = CGRectMake(bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
    NSAttributedString *attachmentAttrStr = [NSAttributedString attributedStringWithAttachment:attachment];
    
    return attachmentAttrStr;
}

@end
